package org.bud.db.dynamic.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * @author shaun
 * @date 2025/4/26
 * @instruction
 */
@Component
@Lazy
public class ApplicationHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationHolder.applicationContext = applicationContext;
    }

    public static Object getBean(String name){
        if(applicationContext == null){
            throw new IllegalArgumentException("application holder get the applicationContext before ApplicationContextAware");
        }
        return ApplicationHolder.applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> tClass){
        if(applicationContext == null){
            throw new IllegalArgumentException("application holder get the applicationContext before ApplicationContextAware");
        }
        return ApplicationHolder.applicationContext.getBean(tClass);
    }
}
